package com.ks.app.admin.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.ks.app.admin.hibernate.KMerBaseSet;
import com.ks.app.admin.hibernate.KsMerAuthen;
import com.ks.app.admin.hibernate.KsMerchantRegist;
import com.ks.app.admin.service.MerchantService;
import com.ks.app.admin.util.ExportExcel;
import com.ks.app.admin.util.Pager;
import com.ks.app.logger.Log4jUtil;

@ParentPackage("struts-default")
@Namespace("")
@Results( {
		@Result(name = "success", location = "/WEB-INF/admin/main.html"),// 主界面
		@Result(name = "error", location = "/WEB-INF/admin/error.jsp"),

		@Result(name = "quit", location = "/WEB-INF/admin/send.jsp"),// 推出系统
		@Result(name = "merinfo", location = "/WEB-INF/admin/merchant/MerInfo.jsp"),// 商家信息
		@Result(name = "singlemerinfo", location = "/WEB-INF/admin/merchant/SingleMerInfo.jsp"),// 单个商家信息
		@Result(name = "baseset", location = "/WEB-INF/admin/merchant/BaseSet.jsp"),// 基本设置
		@Result(name = "integrity", location = "/WEB-INF/admin/merchant/Integrity.jsp"),// 诚信认证
		@Result(name = "inputmer", location = "/WEB-INF/admin/merchant/addMer.jsp"),// 增加商户
		@Result(name = "initedit", location = "/WEB-INF/admin/merchant/EditMer.jsp"),// 修改商户
		@Result(name = "respwd", location = "/WEB-INF/admin/merchant/ResetPassword.jsp"),// 修改密码
		@Result(name = "autheninfo", location = "/WEB-INF/admin/merchant/AuthenInfo.jsp"),// 认证
		@Result(name = "baseset", location = "/WEB-INF/admin/merchant/BaseSet.jsp"),
		@Result(name = "integrity", location = "/WEB-INF/admin/merchant/Integrity.jsp")

})
public class MerchantAction extends BaseAction {
	private String className = "MerchantAction.";
	private static final long serialVersionUID = -2489563019172389982L;
	private Logger logger = Log4jUtil.getBusinessLogger();

	@Resource()
	private MerchantService merchantRgService;
	private long PwdResult;

	/***
	 * 登陆 /admin/merchant/login
	 * 
	 * @return
	 */
	@Action("/admin/merchant/login")
	public String login() {

		String method = "login()";
		logger.info(className + method + "come in login---------");

		try {
			HttpSession ses = request.getSession();
			String mername = request.getParameter("userId");
			String pwd = request.getParameter("userPwd");
			List<KsMerchantRegist> list = merchantRgService.GetKsMer(mername,
					pwd);
			logger.info("show the length of list ----" + list.size());

			KsMerchantRegist kmg = null;

			if (list.size() > 0) {
				kmg = (KsMerchantRegist) list.get(0);
				if (mername.equals(kmg.getMerName())
						&& pwd.equals(kmg.getKsPwd())) {
					ses.setAttribute("merRegist", mername);
					return "success";
				}
			}
		} catch (Exception e) {
			return "quit";
		}
		return "quit";
	}

	/***
	 * 退出 /admin/merchant/quit
	 * 
	 * @return
	 */
	@Action("/admin/merchant/quit")
	public String quit() {
		// 推出系统
		String method = "quit";
		logger.info(className + method + "退出系统--------");
		HttpSession ses = request.getSession();
		ses.removeAttribute("merRegist");
		return "quit";
	}

	/***
	 * 查询商家页面
	 * 
	 * @return
	 */
	@Action("/admin/merchant/inputmer")
	public String inputuser() {

		List<KsMerchantRegist> querylist = merchantRgService.getKsMer();
		request.setAttribute("list_MerInfo", querylist);
		return "inputmer";
	}

	@Action("/admin/merchant/eidtinfo")
	public String eidtinfo() {

		return "eidtinfo";
	}

	/***
	 * 查询所有商家信息
	 * 
	 * @return
	 */
	@Action("/admin/merchant/merinfo")
	public String merinfo() {

		String method = "merinfo";
		logger.info(className + method + "come in the merinfo-----------");

		List<KsMerchantRegist> querylist = new ArrayList<KsMerchantRegist>();
		String merName = request.getParameter("mername");
		String optionId = request.getParameter("oid");

		try {
			// 判断界面是否有传来页码
			String pno = request.getParameter("pno") == null ? "1" : request
					.getParameter("pno").toString().trim();
			String rid = request.getParameter("uiid");
			Pager pager = new Pager();
			int iPageNo = 1;

			try {
				iPageNo = Integer.parseInt(pno);
			} catch (Exception e) {
			}

			pager.setCntOfPage(20);
			pager.setCurPage(iPageNo);

			// 判断过条件查询
			if (merName != null && !"".equals(merName)) {
				System.out.println("the mer name is " + merName);
				querylist = merchantRgService.GetKsMerByMername(merName, pager);
			} else if (optionId != null && !"0".equals(optionId)
					&& !"".equals(optionId)) {
				System.out.println("条件查询，选择操作条件的ID是：" + optionId);
				querylist = merchantRgService.getKsMerByTerm(rid, optionId,
						pager);
				request.setAttribute("oid", optionId);
			} else {
				System.out.println("默认的查询方法------");
				querylist = merchantRgService.GetKsMerList(rid, pager);
			}

			request.setAttribute("list_MerInfo", querylist);
			request.setAttribute("PAGER", pager);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "merinfo";
	}

	@Action("/admin/merchant/checkmer")
	public String checkMer() {
		//
		System.out.println(request.getParameter("mid"));
		return null;
	}

	/***
	 * 添加新用户
	 * 
	 * @return
	 */
	@Action("/admin/merchant/savemer")
	public String savemer() {

		String ksFullName = request.getParameter("merinfo_ksFullName");
		String mername = request.getParameter("merinfo_ksMerName");
		String pwd = request.getParameter("merinfo_ksPwd");
		String merno = request.getParameter("merinfo_ksMerNo");
		String mergroup = request.getParameter("merinfo_ksMerGroup");
		String ksMerRemark = request.getParameter("merinfo_ksMerRemark");
		String merstatus = request.getParameter("merinfo_ksMerStatus");
		String address = request.getParameter("merinfo_ksDetailAdd");
		String detailAdd = request.getParameter("pro").substring(6) + "-"
				+ request.getParameter("selcity").substring(6) + "-"
				+ request.getParameter("area") + "-" + address;
		String phone = request.getParameter("merinfo_ksPhone");

		KsMerchantRegist ksmer = new KsMerchantRegist();
		ksmer.setKsMerAddress(detailAdd);
		ksmer.setKsMerPhone(phone);
		ksmer.setKsCreateTime(new Date());
		ksmer.setKsFullName(ksFullName);
		ksmer.setRemark(ksMerRemark);
		ksmer.setKsPwd(pwd);
		ksmer.setKsMerNo(merno);
		ksmer.setKsMerGroup(mergroup);
		ksmer.setKsMerStatus(merstatus);
		ksmer.setMerName(mername);

		HttpSession ses = request.getSession();
		merchantRgService.addKsMer(ksmer, ses.getAttribute("merRegist")
				.toString());
		return merinfo();
	}

	/***
	 * 删除用户 传uid
	 * 
	 * @return
	 */
	@Action("/admin/merchant/deletemer")
	public String deletemer() {

		String mno = request.getParameter("mno");
		KsMerchantRegist ksmer = (KsMerchantRegist) merchantRgService.GetKsMer(
				mno).get(0);
		merchantRgService.deleteKsMer(ksmer, request.getSession().getAttribute(
				"merRegist").toString());
		return merinfo();
	}

	/***
	 * 修改用户
	 * 
	 * @return
	 */
	@Action("/admin/merchant/editmer")
	public String editmer() {

		String method = "editmer()";
		logger.info(className + method + "come in editmer--------------");

		String ksFullName = request.getParameter("merinfo_ksFullName");
		String merName = request.getParameter("merinfo_mername");
		String pwd = request.getParameter("merinfo_ksPwd");
		String merno = request.getParameter("merinfo_ksMerNo");
		String mergroup = request.getParameter("merinfo_ksMerGroup");
		String remark = request.getParameter("merinfo_ksMerRemark");
		String status = request.getParameter("merinfo_ksMerStatus");
		String address = request.getParameter("merinfo_ksDetailAdd");
		// 获取省市区名称，加上地址拼凑成完成的地址
		String detailAdd = request.getParameter("pro").substring(6) + "-"
				+ request.getParameter("selcity").substring(6) + "-"
				+ request.getParameter("area") + "-" + address;
		String phone = request.getParameter("merinfo_ksMerPhone");
		// 根据界面传过来的隐藏参数ID取得相应的对象
		KsMerchantRegist ksmer = (KsMerchantRegist) merchantRgService.GetKsMer(
				request.getParameter("merinfo_ksMerId")).get(0);
		logger.info(className + method + " remark = " + remark);

		ksmer.setKsCreateTime(ksmer.getKsCreateTime());
		ksmer.setKsMerAddress(detailAdd);
		ksmer.setKsMerPhone(phone);
		ksmer.setKsFullName(ksFullName);
		ksmer.setRemark(remark);
		ksmer.setKsPwd(pwd);
		ksmer.setKsMerNo(merno);
		ksmer.setKsMerGroup(mergroup);
		ksmer.setKsMerStatus(status);
		ksmer.setMerName(merName);
		System.out.println("============================");
		merchantRgService.updateKsMer(ksmer, request.getSession().getAttribute(
				"merRegist").toString());
		return merinfo();

	}

	/***
	 * 查询用户 修改
	 * 
	 * @return
	 */
	@Action("/admin/merchant/initedit")
	public String initedit() {
		// 取得所有用户对象，用于界面校验用户名和编号是否重复
		List<KsMerchantRegist> querylist0 = merchantRgService.getKsMer();
		request.setAttribute("list_MerInfo", querylist0);

		String mno = request.getParameter("mno");
		List<KsMerchantRegist> querylist = merchantRgService.GetKsMer(mno);
		if (querylist.size() > 0) {
			KsMerchantRegist merinfo = querylist.get(0);
			// 截取地址的详细地址部分
			String address = merinfo.getKsMerAddress();
			merinfo.setKsMerAddress(address
					.substring(address.lastIndexOf("-") + 1));
			request.setAttribute("merRegist", merinfo);
			request.setAttribute("mername", merinfo.getMerName());
		}
		return "initedit";
	}

	@Action("/admin/merchant/respwd")
	public String respwd() {
		try {
			String mername = request.getSession().getAttribute("merRegist")
					.toString();
			KsMerchantRegist ksMer = (KsMerchantRegist) merchantRgService
					.GetKsMer(mername, "").get(0);
			request.setAttribute("ksMer", ksMer);
			request.setAttribute("PwdResult", PwdResult);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "respwd";
	}

	/***
	 * 修改用户密码
	 * 
	 * @return
	 */
	@Action("/admin/merchant/upwd")
	public String upwd() {

		try {
			PwdResult = 0;
			List<KsMerchantRegist> lu = merchantRgService.GetKsMer(request
					.getParameter("merinfo_ksMerName"), "");
			String merinfo_Oripassword = request
					.getParameter("merinfo_Oripassword");

			if (lu.size() > 0) {
				KsMerchantRegist uu = lu.get(0);
				// 判断旧密码是否正确，如果正确重置为新密码
				if (merinfo_Oripassword.trim().equals(uu.getKsPwd().trim())) {
					uu.setKsPwd(request.getParameter("merinfo_newPassword"));
					PwdResult = merchantRgService.updateKsMer(uu, request
							.getSession().getAttribute("merRegist").toString());
				} else {
					PwdResult = -1;
					return respwd();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return respwd();
	}

	@Action("/admin/merchant/merAuthen")
	public String authenInfo() {

		String method = "authenInfo";
		logger.info(className + method
				+ "-------come in the authenInfo-----------");

		List<KsMerAuthen> querylist = new ArrayList<KsMerAuthen>();
		String merName = request.getParameter("mername");
		String optionId = request.getParameter("oid");

		try {
			// 判断界面是否有传来页码
			String pno = request.getParameter("pno") == null ? "1" : request
					.getParameter("pno").toString().trim();
			String rid = request.getParameter("uiid");
			Pager pager = new Pager();
			int iPageNo = 1;
			try {
				iPageNo = Integer.parseInt(pno);
			} catch (Exception e) {
			}
			pager.setCntOfPage(20);
			pager.setCurPage(iPageNo);

			// 判断过条件查询
			if (merName != null && !"".equals(merName)) {
				System.out.println("the mer name is " + merName);
				querylist = merchantRgService
						.GetAuthenByMername(merName, pager);
			} else if (optionId != null && !"0".equals(optionId)
					&& !"".equals(optionId)) {
				System.out.println("条件查询，选择操作条件的ID是：" + optionId);
				// querylist =
				// merchantRgService.getKsMerByTerm(rid,optionId,pager);
			} else {
				System.out.println("默认的查询方法------");
				querylist = merchantRgService.GetAuthenList(rid, pager);
			}
			request.setAttribute("list_MerInfo", querylist);
			request.setAttribute("PAGER", pager);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "autheninfo";
	}

	@Action("/admin/merchant/exportExcel")
	public String exportExcel() {

		System.out
				.println("use this method to exportExcel the merchant information");
		List<KsMerchantRegist> list = merchantRgService.getKsMer();
		System.out.println(list.size());
		try {
			ExportExcel.write2Excel(list, "merchant", response);
		} catch (Exception e) {
		}
		return "";
	}

	@Action("/admin/merchant/singleInfo")
	public String singleInfo() {

		String method = "singleInfo";
		logger.info(className + method
				+ "--------come in check operation-------");

		KsMerchantRegist mer = null;
		List<KsMerchantRegist> list = null;
		String oid = request.getParameter("coid");
		String mno = request.getParameter("mno");
		logger.info(className + method + "--oid=" + oid + "-------mno=" + mno);

		if (oid != null && !"".equals(oid)) {
			// 根据不同的操作ID进行不同的操作
			list = merchantRgService.GetKsMer(mno);
			mer = list.get(0);
			System.out.println("选择的操作ID是=" + oid);
			switch (Integer.parseInt(oid)) {
			case 1:
				request.setAttribute("KsMer", mer);
				return "singlemerinfo";
			case 2:
				request.setAttribute("KsMer", mer);
				return "baseset";
			case 3:
				request.setAttribute("KsMer", mer);
				return "integrity";
			}
		} else {
			// 如果没有操作ID则进行下面跳转
			String mno1 = request.getParameter("mno");
			list = merchantRgService.GetKsMer(mno1);
			mer = list.get(0);
			request.setAttribute("KsMer", mer);
			return "singlemerinfo";
		}
		return "error";
	}

	@Action("/admin/merchant/baseset")
	public String updateSet() {

		String method = "updateSet()";
		logger.info(className + method
				+ "update the rate and discount of merchant");

		String discount = request.getParameter("discount") + "%";
		String rate = request.getParameter("mer_commission") + "%";
		String mno = request.getParameter("mno");
		logger.info(className + method + "get the parameter discount = "
				+ discount + ",rate=" + rate + ",mid=" + mno);

		// 通过界面传来的mid取得关联的对象KMerBaseSet
		KsMerchantRegist mer = merchantRgService.GetKsMer(mno).get(0);
		KMerBaseSet base = mer.getMerBaseSetID();
		base.setDiscount(discount);
		base.setCommission(rate);
		request.setAttribute("KsMer", mer);
		merchantRgService.updateSet(base, mer.getMerName());

		return "baseset";
	}

	@Action("/admin/merchant/integrity")
	public String updateinteg() {

		String method = "updateinteg()";
		String mno = request.getParameter("mno");
		String mer_deposit = request.getParameter("mer_deposit");
		String approve = request.getParameter("integrity");
		String mer_level = request.getParameter("mer_level");

		logger.info(className + method + "get the parameter mer_deposit = "
				+ mer_deposit + ",mer_level = " + mer_level + ", approve = "
				+ approve);

		KsMerchantRegist mer = (KsMerchantRegist) merchantRgService.GetKsMer(
				mno).get(0);
		KMerBaseSet base = mer.getMerBaseSetID();
		if(mer_deposit != null && !"".equals(mer_deposit)){
			base.setDeposit(mer_deposit);
		}
		if(mer_level != null && !"".equals(mer_level)){
			base.setMerlevel(mer_level);
		}
		if(approve != null && !"".equals(approve)){
			base.setApprove(approve);
		}
		request.setAttribute("KsMer", mer);
		merchantRgService.updateSet(base, mer.getMerName());

		return "integrity";
	}

}
